package com.zhengbing.tj.service.impl;

import com.zhengbing.tj.entity.Role;
import com.zhengbing.tj.entity.UserRole;
import com.zhengbing.tj.mapper.RoleMapper;
import com.zhengbing.tj.service.RoleService;
import com.zhengbing.tj.service.UserRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.zhengbing.tj.annotation.AuditLogRecord;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 角色服务实现类
 * 实现角色相关的业务逻辑
 *
 * @author zhengbing
 * @date 2024-08-22
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {
    
    @Autowired
    private UserRoleService userRoleService;
    
    @Override
    public List<Role> getRolesByUserId(Long userId) {
        // 根据用户ID查询角色ID列表
        List<Long> roleIds = userRoleService.selectRoleIdsByUserId(userId);
        if (roleIds.isEmpty()) {
            return new ArrayList<>();
        }
        // 根据角色ID列表查询角色信息
        return listByIds(roleIds);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    @AuditLogRecord(entityType = "user_role", operationType = "update", description = "更新用户角色关系", idParamIndex = 0)
    public void saveUserRoles(Long userId, List<Long> roleIds) {
        // 先删除用户原有的角色关系
        userRoleService.removeByUserId(userId);
        
        // 保存新的用户角色关系
        if (roleIds != null && !roleIds.isEmpty()) {
            List<UserRole> userRoles = roleIds.stream().map(roleId -> {
                UserRole userRole = new UserRole();
                userRole.setUserId(userId);
                userRole.setRoleId(roleId);
                return userRole;
            }).collect(Collectors.toList());
            
            // 使用批量插入，提高性能
            userRoleService.saveBatch(userRoles);
        }
    }
}